#!/usr/bin/env python
# -*- coding: UTF-8 -*-
'''
@Project ：self-practice 
@File    ：consumer.py
@IDE     ：PyCharm 
@Author  ：w50011605
@Email   ：wangqiyu1@xfusion.com
@Date    ：2025/6/25 10:40 
'''


import threading
import pika
from RabbitMQConnection import RabbitMQConnection

def callback(ch, method, properties, body):
    print(f"[x] Received {body}")


def listen_for_input(channel):
    while True:
        user_input = input()
        if user_input.lower() == "quit":
            print("Exiting...")
            channel.stop_consuming()
            break

def init_input_thread(channel):
    # 创建线程启动监听
    input_thread = threading.Thread(target=listen_for_input, args=(channel,))
    input_thread.daemon = True  # 程序退出时线程也退出
    input_thread.start()

def select_communication_mode(mode: str, rmq: RabbitMQConnection):
    """根据输入选择通信模式"""
    if mode == "base":
        base_queue_communication(rmq)
    elif mode == "topic":
        topic_communication(rmq)
    else:
        print("Invalid communication mode selected.")

def base_queue_communication(rmq: RabbitMQConnection):
    """基本队列通信示例"""
    channel = rmq.get_channel()
    channel.queue_declare(queue="test_queue")

    # 初始化线程启动监听
    init_input_thread(channel)

    # 消费消息
    channel.basic_consume(queue='test_queue', on_message_callback=callback, auto_ack=True)  # 使用 callback 函数对象
    print('[*] Waiting for messages. To exit press quit')
    channel.start_consuming()


"""
    《手动持久化》
    def callback(ch, method, properties, body):
    print(f" [x] Processing {body}")
    # 模拟耗时任务
    import time
    time.sleep(5)
    print(" [x] Done")
    ch.basic_ack(delivery_tag=method.delivery_tag)  # 手动确认

    channel.basic_consume(
        queue='task_queue',
        on_message_callback=callback,
        auto_ack=False  # 关闭自动确认
)
"""
def topic_communication(rmq: RabbitMQConnection):
    """基于主题的交换机通信示例"""
    channel = rmq.get_channel()

    # 声明交换机
    channel.exchange_declare(exchange='topic_logs', exchange_type='topic')

    # 初始化线程启动监听
    init_input_thread(channel)

    # 创建临时队列（关闭连接后自动删除）
    result = channel.queue_declare(queue='', exclusive=True)
    queue_name = result.method.queue

    # 绑定队列到交换机，监听特定路由键
    routing_key = 'user.notification.*'  # 通配符匹配
    channel.queue_bind(
        exchange='topic_logs',
        queue=queue_name,
        routing_key=routing_key
    )

    channel.basic_consume(
        queue=queue_name,
        on_message_callback=callback,
        auto_ack=True
    )

    print(' [*] Waiting for logs. To exit press quit')
    channel.start_consuming()


# 使用类来管理RabbitMQ连接
rmq = RabbitMQConnection(host='localhost')

# 选择通信模式
mode = input("Enter communication mode ('base' or 'topic'): ").lower()

select_communication_mode(mode, rmq)

# 关闭连接
rmq.close()
